package javaTest05.exercise01.udp;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class UdpClient {
    public static void main(String[] args) {
        try {

            DatagramSocket client =new DatagramSocket();//创建套接字
            System.out.println("客户端已启动...");

            String path = "src/javaTest05/resource/my.docx";
            InetAddress ip = InetAddress.getLocalHost();//获取本地ip
            int port = 2468;//服务端端口

            sendFileToRemote(path,ip,port,client);//将文件发送至服务端
            System.out.println("文件发送成功");
            client.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void sendFileToRemote(String path,InetAddress ip,int port,DatagramSocket client) throws IOException {//分片传送

        FileInputStream in = new FileInputStream(path);
        byte[] buffer = new byte[1024];//缓存
        int count;

        DatagramPacket sendPacket = new DatagramPacket(new byte[]{},0,0,ip,port);//创建数据报文

        while ((count = in.read(buffer)) != -1){//因UDP传输限制大小,采用分片传输文件 一次最多发送1kb
            sendPacket.setData(buffer,0,count);//要传输的字节数组
            client.send(sendPacket);//发送报文
        }

        String end = "file transfer end;";//结束标志
        byte[] endByte = end.getBytes(StandardCharsets.UTF_8);

        sendPacket.setData(endByte,0, endByte.length);//作为结束标志
        client.send(sendPacket);//发送结束标志

        in.close();
    }



}
